﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using Newtonsoft.Json.Linq;

namespace BlogsAPI.BlogsYandex
{

    /// <summary>
    /// Работа с различными переводами
    /// </summary>
    public static class TranslateAPI
    {
        /// <summary>
        /// Вызов функции перевода
        /// </summary>
        /// <param name="from">TwoLetterISOLanguageName</param>
        /// <param name="to">TwoLetterISOLanguageName</param>
        /// <remarks>https://translate.yandex.net/api/v1.5/tr.json/translate ? 
        //       key=<API key>
        //& text=<text to translate>
        //& lang=<translation direction>
        //& [format=<text format>]
        //& [options=<translation options>]
        //& [callback=<name of the callback function>]</remarks>
        /// <see cref="https://tech.yandex.com/translate/doc/dg/reference/translate-docpage/"/>
        /// <returns></returns>
        public static string Call(string apiKey, string text, string from, string to)
        {
            try
            {
                using (var client = new WebClient {Encoding = Encoding.UTF8})
                {
                    var url = String.Format(
                        "https://translate.yandex.net/api/v1.5/tr.json/translate?key={0}&text={1}&lang={2}-{3}",
                        apiKey,
                        HttpUtility.UrlEncode(text),
                        from,
                        to);
                    var reply = client.DownloadString(url);
                    var json = JObject.Parse(reply);
                    return json["text"].First.Value<string>();
                }
            }
            catch (Exception err)
            {
                Debug.Write(err);
            }
            return null;
        }

        public static string Call(string apiKey, string text, CultureInfo from, CultureInfo to)
        {
            return Call(apiKey, text, from.TwoLetterISOLanguageName, to.TwoLetterISOLanguageName);
        }
}
}
